<template>
  <div class="device-wrap" @dblclick="goToTask">
    <DiagramPicker
      v-if="monitorDevice && monitorDevice.fileType === 2"
      :monitorDevice="monitorDevice"
      :otherPoints="allPoints"
      :pointsFontColor="setupOption.pointsFontColor"
      :pointsFontSize="setupOption.pointsFontSize"
      :isPreview="true"
      :backgroundColor="setupOption.backgroundColor"
    />

    <ImagePicker
      v-if="monitorDevice && monitorDevice.fileType === 1"
      :monitorDevice="monitorDevice"
      :otherPoints="allPoints"
      :pointsFontColor="setupOption.pointsFontColor"
      :pointsFontSize="setupOption.pointsFontSize"
      :isPreview="true"
      :backgroundColor="setupOption.backgroundColor"
    />
  </div>
</template>

<script setup lang="ts">
import { MonitorDeviceApi } from '@/api/vmiot/monitordevice'
import { TaskApi } from '@/api/vmiot/task'
import DiagramPicker from '@/views/vmiot/task/DiagramPicker.vue'
import ImagePicker from '@/views/vmiot/task/ImagePicker.vue'
import { ref, computed, watch, onMounted } from 'vue'

// Props
const props = defineProps<{
  widgetOptions: any
  isPreview?: Boolean
  tenantId?: number
  isShare?: boolean
}>()

const emit = defineEmits([])
const monitorDeviceList = ref<any[]>([])
const taskData = ref<any>({})
const router = useRouter()

const setupOption = computed(() => {
  return props.widgetOptions.setup
})

const getMonitorDeviceList = async () => {
  try {
    const deviceList = props.isShare
      ? await MonitorDeviceApi.getAllMonitorDeviceListByShare(props.tenantId)
      : await MonitorDeviceApi.getAllMonitorDeviceList()
    monitorDeviceList.value = deviceList
  } catch {}
}

const monitorDevice = computed(() => {
  if (props.isPreview) {
    return monitorDeviceList.value.find((item) => item.id === taskData.value.monitorDeviceId)
  } else {
    return (
      props.widgetOptions.data.monitorDevice || {
        fileType: 2,
        devicePic: '/transModel.gltf'
      }
    )
  }
})

const allPoints = ref<any[]>([])

const getTaskDetail = async () => {
  if (props.widgetOptions.data.taskId) {
    const res = props.isShare
      ? await TaskApi.getTaskByShare(props.widgetOptions.data.taskId)
      : await TaskApi.getTask(props.widgetOptions.data.taskId)
    taskData.value = res
    const flowData = JSON.parse(res.content)
    allPoints.value = flowData.nodes.filter((item) => item.type === 'output')
  }
}

const goToTask = () => {
  if (props.widgetOptions.data.taskId) {
    const routeUrl = router.resolve({
      path: '/task/detail',
      query: { id: props.widgetOptions.data.taskId }
    })
    window.open(routeUrl.href, '_blank')
  }
}

onMounted(() => {
  if (props.isPreview) {
    getMonitorDeviceList()
    getTaskDetail()
  } else {
    allPoints.value = props.widgetOptions.data.pointsData
  }
})
</script>

<style scoped lang="scss">
.device-wrap {
  width: 100%;
  height: 100%;
}
</style>
